package com.dragon.english_practice_back.handler;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.dragon.english_practice_back.entity.LoginUserDetails;
import com.dragon.english_practice_back.entity.User;
import com.dragon.english_practice_back.mapper.RoleMapper;
import com.dragon.english_practice_back.mapper.UserMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.Objects;

@Slf4j
@Service
public class UserDetailsServiceImpl implements UserDetailsService {
    @Autowired
    UserMapper userMapper;
    @Autowired
    RoleMapper roleMapper;
    @Override
    public UserDetails loadUserByUsername(String email) throws UsernameNotFoundException {
        //创建查询
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("email", email);
        User user = this.userMapper.selectOne(queryWrapper);

        //账户不存在
        if (Objects.isNull(user)){
            log.error("at user email:{} not exist", email);
            throw new UsernameNotFoundException("access failure! email: " + email + "is not exist");
        }

        //创建UserDetails
        LoginUserDetails loginUserDetails = new LoginUserDetails();
        loginUserDetails.setUser(user);

        //插入角色信息
        loginUserDetails.setRole(this.roleMapper.roleStringsByUserId(user.getId()));


        return loginUserDetails;
    }
}
